<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\helper\Time;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class Teacher extends Ques
{

    /**
     * Teacher模型对象
     * @var \app\admin\model\Teacher
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Teacher;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 统计未完成
     */
    public function ana(){

        $filter = json_decode(input('filter'),true);
        $timeArr = explode(' - ',$filter['create_time']);
//            var_dump($timeArr);
        if(isset($timeArr[1])){
            $timestampArr = [
                strtotime($timeArr[0]),strtotime($timeArr[1])
            ];
        }else{
            $timestampArr = Time::today();
        }


        $whereQues = [];
        $whereTea = [];


        if(isset($this -> sess['teacherIds'])){
            $whereQues['teacher_id'] = ['in',$this -> sess['teacherIds']];
            $whereTea['a.id'] = ['in',$this -> sess['teacherIds']];
        }

        $reported = (new \app\admin\model\QuesTeacher()) -> where($whereQues) -> whereBetween('create_time',$timestampArr) -> column('teacher_id');

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where_ = [];
            if(isset($filter['college_id']) && $filter['college_id']){
                $departmentId = (new \app\admin\model\Department) -> where('college_id',$filter['college_id']) -> column('id');
                $where_['department_id'] = ['in',$departmentId];
            }

            if(isset($filter['department_id'])){
                if(isset($where_['department_id'])) unset($where_['department_id']);
                $where_['department_id'] = ['=',$filter['department_id']];
            }


            $total = $this->model
                -> alias('a')
                -> where($whereTea)
                -> whereNotIn('a.id',$reported)
                ->where($where_)
                ->join('department b','b.id=a.department_id')
                ->join('college c','c.id=b.college_id')
                ->field('nickname,tel,b.name as department_name ,c.name as college_name')
                ->order('a.id','desc')
                ->count();

            $list = $this->model
                -> alias('a')
                -> where($whereTea)
                -> whereNotIn('a.id',$reported)
                ->where($where_)
                ->join('department b','b.id=a.department_id')
                ->join('college c','c.id=b.college_id')
                ->field('nickname,tel,b.name as department_name ,c.name as college_name')
                ->order('a.id','desc')
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }


        $allcount = (new \app\admin\model\Teacher()) -> alias('a') -> where($whereTea) -> count();
        $reportedcount = count($reported);
        $notreportedallcount = $allcount - $reportedcount;

        $today = Time::today();
        $todayStr = date("Y-m-d H:i:s",$today[0]).' - '.date("Y-m-d H:i:s",$today[1]);
        if(isset($this ->sess['college_id'])){
            $this -> assign('collegestr','id='.$this -> sess['college_id']);
        }else{
            $this -> assign('collegestr','');
        }
        $this -> assign('today', $todayStr);
        $this -> assign('allcount',$allcount);
        $this -> assign('reportedcount',$reportedcount);
        $this -> assign('notreportedallcount',$notreportedallcount);
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $department = \app\admin\model\Department::get($params['department_id']);
                $params['department_name'] = $department -> name;
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $colleges = \app\admin\model\College::all();
        $collegesArr = [];
        foreach ($colleges as $k =>$v){
            $collegesArr[$v['id']] = $v -> name;
        }


        $this -> assign('colleges',$collegesArr);
        return $this->view->fetch();
    }


    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $department = \app\admin\model\Department::get($params['department_id']);
                $params['department_name'] = $department -> name;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $colleges = \app\admin\model\College::all();
        $collegesArr = [];
        foreach ($colleges as $k =>$v){
            $collegesArr[$v['id']] = $v -> name;
        }

        $depart = \app\admin\model\Department::get($row -> department_id);

        $departments = \app\admin\model\Department::all(['college_id'=>$depart -> college_id]);
        $departmentArr = [];
        foreach ($departments as $k => $v){
            $departmentArr[$v['id']] = $v -> name;
        }


        $this -> assign('depart',$depart);
        $this -> assign('departments',$departmentArr);
        $this -> assign('colleges',$collegesArr);
        $this->view->assign("row", $row);
        return $this->view->fetch('edit');
    }



    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $where_ = [];
        if(isset($this -> sess['teacherIds'])){
            $where_['id'] = ['in',$this -> sess['teacherIds']];
        }
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            if(input('college_id')){
                $college_id = input('college_id');
                $departmentId = (new \app\admin\model\Department) -> where('college_id',$college_id) -> column('id');
                $where_['department_id'] = ['in',$departmentId];
            }

            $groupIds = $this->auth->getGroupIds();
            //学院单位
            if($groupIds[0]==7)
            {
                $info = (new \app\admin\model\College) -> where('name',$this->auth->username) -> find();
                if(isset($info))
                {
                    $departmentId = (new \app\admin\model\Department) -> where('college_id',$info['id']) -> column('id');
                    $where_['department_id'] = ['in',$departmentId];
                }
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($where_)
                ->order($sort, $order)
                ->count();

            $list = $this->model->with('department.college')
                ->where($where)
                ->where($where_)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function import()
    {
        $filepath = input('file');
        $college_id = input('college_id');
        $department_id = input('department_id');

        // $filepath = '/uploads/20200224/723a787dea5e34700821894b87af5093.xlsx';
        // $college_id = 74;
        // $department_id = 490;
        $fieldname = ['nickname','tel','type'];
        $extraparams = ['department_id'=>$department_id];
        if($college_id && $college_id)
        {
            $data = $this->importExcel($filepath, 2, 0,  $fieldname,$extraparams);
        }

        foreach ($data as $key => $value) {
            $row = $this->model->where(['nickname'=>$value['nickname'],'tel'=>$value['tel']])->find();
            if($row)
            {
                Db::name('teacher')->where('id', $row['id'])->update($value);
            }
            else
            {
                Db::name('teacher')->insert($value);
            }
        }

        $this->success('上传成功');
    }

    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if($this -> auth -> id != 1 && $v -> type != 3){
                        continue;
                    }
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted').' 教职工只有管理员可以删除');
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
